﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Data.Schema.Sql.SchemaModel;
using TFDP.Common;
using System.IO;

namespace TFDP.Processing
{
    public static class ProcessorExtensions
    {
        public static bool HasHistoryTable(this ISqlTable table)
        {
            return table.Model.Has<ISqlTable>(String.Format("{0}Historie", table.GetFullName()));
        }

        public static bool HasSystemColumns(this ISqlTable table)
        {
            List<ISqlColumn> columns = table.GetColumns(ColumnFlags.SystemColumns);

            return !(columns == null || columns.Count == 0);
        }

        public static bool HasCustomTriggerContent(this ISqlTable table, string action = "", bool exact = false)
        {
            // Is this a scriptsourced element?
            if (table.PrimarySource == null)
                return false;

            string schemaName = table.GetSchemaName();

            string path = table.PrimarySource.SourceName;

            int index = path.IndexOf(schemaName, StringComparison.InvariantCultureIgnoreCase);

            if (index >= 0)
            {
                path = path.Substring(0, index + schemaName.Length);
                path = Path.Combine(path, "Tables", "Triggers", "Custom");

                string[] files = Directory.GetFiles(path, String.Format("{0}{1}{2}.sql", table.GetName(), action, exact ? "" : "*"));

                return (files.Length > 0);
            }
            else
                return false;
        }
    }
}
